package cn.xiaoyu.locationmanagertool;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 功能描述：通过手机信号获取基站信息
 * # 通过TelephonyManager 获取lac:mcc:mnc:cell-id
 * # MCC，Mobile Country Code，移动国家代码（中国的为460）；
 * # MNC，Mobile Network Code，移动网络号码（中国移动为0，中国联通为1，中国电信为2）；
 * # LAC，Location Area Code，位置区域码；
 * # CID，Cell Identity，基站编号；
 * # BSSS，Base station signal strength，基站信号强度。
 *
 * @author android_ls
 */
public class MainActivity extends Activity {

    private static final String TAG = "GSMCellLocationActivity";

    private TextView tvResult = null;

    private StringBuffer sb = new StringBuffer();

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    private String[] permissions = { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION };
    private AlertDialog dialog;

    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            doLoc();
        }
    }

    // 提示用户去应用设置界面手动开启权限

    private void showDialogTipUserGoToAppSettting() {

        dialog = new AlertDialog.Builder(this).setTitle("存储权限不可用").setMessage("请在-应用设置-权限-中，允许支付宝使用存储权限来保存用户数据").setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 跳转到应用设置界面
                goToAppSetting();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }

    //
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            int coarseLocation = ContextCompat.checkSelfPermission(this, permissions[0]);
            int fineLocation = ContextCompat.checkSelfPermission(this, permissions[1]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (coarseLocation != PackageManager.PERMISSION_GRANTED || fineLocation != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, permissions, 321);
            }
        }


        // 获取基站信息
        findViewById(R.id.btn_obtain_cell_info).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {


                int coarseLocation = ContextCompat.checkSelfPermission(MainActivity.this, permissions[0]);
                int fineLocation = ContextCompat.checkSelfPermission(MainActivity.this, permissions[1]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (coarseLocation != PackageManager.PERMISSION_GRANTED || fineLocation != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
                    ActivityCompat.requestPermissions(MainActivity.this, permissions, 321);
                } else {
                    doLoc();
                }
            }
        });

        // 获取GPS信息
        findViewById(R.id.btn_obtain_gps).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startBaiduMap();
            }
        });

        tvResult = (TextView) findViewById(R.id.tv_result);
        tvResult.setMovementMethod(new ScrollingMovementMethod());
    }

    private void doLoc() {

        TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        // 返回值MCC + MNC
        String operator = mTelephonyManager.getNetworkOperator();
        int mcc = Integer.parseInt(operator.substring(0, 3));
        int mnc = Integer.parseInt(operator.substring(3));

        // 中国移动和中国联通获取LAC、CID的方式
        GsmCellLocation location = (GsmCellLocation) mTelephonyManager.getCellLocation();
        int lac = location.getLac();
        int cellId = location.getCid();

        Log.i(TAG, " MCC = " + mcc + "\t MNC = " + mnc + "\t LAC = " + lac + "\t CID = " + cellId);

        // 中国电信获取LAC、CID的方式
                /*CdmaCellLocation location1 = (CdmaCellLocation) mTelephonyManager.getCellLocation();
                lac = location1.getNetworkId();
                cellId = location1.getBaseStationId();
                cellId /= 16;*/

        // 获取邻区基站信息
        List<NeighboringCellInfo> infos = mTelephonyManager.getNeighboringCellInfo();
        sb.append("获取邻区基站数" + infos.size() + "条\n");
        // 根据邻区总数进行循环
        for (NeighboringCellInfo info1 : infos) {
            // 取出当前邻区的LAC
            sb.append("\tLAC : " + info1.getLac());
            // 取出当前邻区的CID
            sb.append("\n\tCID : " + info1.getCid());
            sb.append("\n\t信号强度 BSSS : " + (-113 + 2 * info1.getRssi()) + "\n\n"); // 获取邻区基站信号强度
        }

        Log.i(TAG, " 获取邻区基站信息:" + sb.toString());
        tvResult.setText(sb.toString());
    }

    //用于定位的方法
    private void startBaiduMap() {
        //权限检查
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        //获取定位管理器
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取位置信息
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        //更新位置信息
        upLoadInfo(location);
        //设置LocationManager的监听事件
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 8, new LocationListener() {

            /** 当地理位置发生改变的时候调用 */
            @Override
            public void onLocationChanged(Location location) {
                Log.d("GPS_SERVER", "位置信息改变");
                upLoadInfo(location);
            }

            /** 当状态发生该变的时候调用 */
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                Log.d("GPS_SERVER", "状态信息改变");
            }

            /** 当定位提供者启用的时候调用 */
            @Override
            public void onProviderEnabled(String provider) {
                Log.d("GPS_SERVER", "定位提供者启用");
            }

            /** 当定位提供者禁止的时候调用 */
            @Override
            public void onProviderDisabled(String provider) {
                Log.d("GPS_SERVER", "定位提供者禁用");
            }
        });
    }

    /**
     * 输出经纬度的信息
     */
    private void upLoadInfo(Location location) {
        if (location != null) {
            double Longitude = location.getLongitude();
            double Latitude = location.getLatitude();
            sb.append(simpleDateFormat.format(new Date()) + "   经度：" + Longitude + "\t" + "纬度：" + Latitude + "\n");
            tvResult.setText(sb.toString());
        }
    }
}
